package com.fwtai.service;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

/**
 * 获取bean获取对象
 * @作者 田应平
 * @版本 v1.0
 * @创建时间 2022年2月24日 13:18:31
 * @QQ号码 444141300
 * @Email service@yinlz.com
 * @官网 <url>http://www.fwtai.com</url>
*/
@Component
public class SpringContextHolder implements ApplicationContextAware{

  private static ApplicationContext springContext;

  @Override
  public void setApplicationContext(final ApplicationContext context) throws BeansException{
    SpringContextHolder.springContext = context;
  }

  /**
   * 返回spring上下文环境对象
   * @return ApplicationContext
  */
  public static ApplicationContext getSpringContext(){
    return springContext;
  }

  /**
   * 按名称获取spring bean
   * @param name
   * @return
  */
  public static Object getBean(final String name){
    return springContext.getBean(name);
  }

  /**
   * 按类型获取spring bean
   * @param requiredType
   * @return
  */
  public static <T> T getBean(final Class<T> requiredType){
    return springContext.getBean(requiredType);
  }

  /**
   * 发布事件到spring
   * @param event
   */
  public static void pushEvent(final ApplicationEvent event) {
    springContext.publishEvent(event);
  }
}